import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request,user, response):
    """合并购物车（登录时将未登录的cookie购物车数据合并到登录用户redis购物车中）"""
    # 1.拿到cookie进行base64解码
    #判断是否有购物车cookie
    if request.COOKIES.get('carts') is None:
        return response
    carts_cookie = request.COOKIES.get('carts').replace("'", '')[1:].encode('utf-8')  # 浏览器把我们二进制数据改为了str，我们需要格式化一下数据
    cookie_carts = pickle.loads(base64.b64decode(carts_cookie))  # 进行base64解码
    # 2.cookie中没有购物车数据，不需要合并，直接返回response
    if not len(cookie_carts) > 0:
        return response
    # 3.cookie中有数据，拿指定用户redis购物车数据
    cli=get_redis_connection('carts')
    redis_carts=cli.hgetall(user.id)
    cli_pip=cli.pipeline()
    # 4.进行数据合并，合并规则：
    for sku_id in cookie_carts:
    #     4.1 cookie有redis没有的商品直接合并
        if not sku_id.encode() in redis_carts.keys():
            if cookie_carts[sku_id]['selected']:
                cli_pip.hset(user.id,sku_id,abs(int(cookie_carts[sku_id]['count'])))
            else:
                cli_pip.hset(user.id, sku_id, -abs(int(cookie_carts[sku_id]['count'])))
        else:
    #     4.2 cookie有redis有，看选择状态，
            if (cookie_carts[sku_id]['selected'] and int(redis_carts[sku_id.encode()]) > 0) or (not cookie_carts[sku_id]['selected'] and int(redis_carts[sku_id.encode()]) < 0):
    #         4.2.1选择状态相同数量相加直接合并
                if cookie_carts[sku_id]['selected']:
                    cli_pip.hset(user.id,sku_id,abs(int(cookie_carts[sku_id]['count'])+int(redis_carts[sku_id.encode()].decode())))
                else:
                    cli_pip.hset(user.id, sku_id, -abs(-abs(int(cookie_carts[sku_id]['count'])) + int(redis_carts[sku_id.encode()].decode())))
            else:
    #         4.2.2选择状态不相同，以cookie商品数量为准
                if cookie_carts[sku_id]['selected']:
                    cli_pip.hset(user.id,sku_id,cookie_carts[sku_id]['count'])
                else:
                    cli_pip.hset(user.id, sku_id, -abs(int(cookie_carts[sku_id]['count'])))
    cli_pip.execute()
    # 5.删除cookie
    response.delete_cookie('carts')
    # 6.返回response
    return response
